<script lang="ts">
    import { useFormItemContext } from "../FormItem/FormItem.svelte";
    import { Radio } from "../Radio";
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import type { RadioGroupProps } from "./RadioGroup";

    let { value = $bindable(), ...props }: RadioGroupProps = $props();
    const ctx = useFormItemContext();
    let thumbStyle = $state("");
    let wrap: HTMLElement;

    const classList = $derived(
        useClassList(props, "cm-radio-group", {
            "cm-radio-group-stack": props.block,
            "cm-radio-group-stick": props.stick,
            "cm-checkbox-group-card": props.type === "card",
            "cm-checkbox-group-pure-card": props.type === "pureCard",
        })
    );

    const _onChange = (checked: boolean, v: any) => {
        if (props.disabled) {
            return;
        }
        value = v;
        props.onchange?.(v);
        ctx?.onFieldChange?.();
    };

    const textField = props.textField ?? "label";
    const valueField = props.valueField ?? "value";

    const checked = (item: any) => {
        return value === item[valueField];
    };

    $effect(() => {
        const val: any = value ?? "";
        let currentIndex: number = -1;
        for (let i = 0; i < props.data.length; i++) {
            const item = props.data[i];
            const checked = val === item[valueField];
            checked ? (currentIndex = i) : false;
        }

        const eles = wrap.querySelectorAll(".cm-radio");

        const ele = eles[currentIndex];
        if (!ele) {
            return;
        }
        const rect = ele.getBoundingClientRect();
        const wrapRect = wrap.getBoundingClientRect();
        const left = rect.left - wrapRect.left;
        const width = rect.width;
        const ret = {
            width: `${width}px`,
            left: `${left}px`,
        };
        thumbStyle = useStyle({}, ret);
    });
</script>

<div class={classList} style={props.style} bind:this={wrap}>
    {#if props.stick}
        <div class="cm-radio-group-thumb" style={thumbStyle}></div>
    {/if}
    {#each props.data as item (item[valueField])}
        <Radio
            disabled={props.disabled || item.disabled}
            type={props.apparence || "radio"}
            value={item[valueField]}
            checked={checked(item)}
            label={item[textField]}
            extra={item.extra}
            onchange={_onChange}
        />
    {/each}
</div>
